package com.platform.module.common.utils;

import com.platform.module.common.base.CommonResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TokenGenerator {
    /** 过期时间 毫秒*/
    public static final int TOKEN_TIME = 24*60*60*1000;
    private static final Logger log = LoggerFactory.getLogger(TokenGenerator.class);
    private static final Pattern BLANK_OR_LINE = Pattern.compile("\\s*|\t|\r|\n");
    private static final byte[] iv = new byte[]{93, 81, 122, -23, 47, 50, 17, 103};


    public static byte[] getKeyBytes(String keyString) {
        byte[] b = new byte[24];
        byte[] key = keyString.getBytes();
        int count = keyString.getBytes().length;
        int i;
        for (i = 0; i < count; ++i) {
            b[i] = key[i];
        }
        for (i = count; i < 24; ++i) {
            b[i] = 32;
        }
        return b;
    }

    public static String createDigest(String src) {
        String ret = "";

        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            sha.update(src.getBytes());
            ret = Base64.getEncoder().encodeToString(sha.digest());
        } catch (Exception var3) {
            log.error("异常信息", var3);
        }

        return ret;
    }

    public static String[] authToken(String authentication, String appId, String tokenKey) {
        String[] str = new String[3];

        try {
            byte[] tripleKey = getKeyBytes(tokenKey);
            SecretKey secretKey = new SecretKeySpec(tripleKey, "DESede");
            Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            IvParameterSpec ivparam = new IvParameterSpec(iv);
            byte[] auth = Base64.getDecoder().decode(authentication);
            cipher.init(2, secretKey, ivparam);
            String text = new String(cipher.doFinal(auth));
            String[] textValue = text.split("\\$");
            if (textValue.length == 2) {
                HashMap<String, String> map = new HashMap<>();
                String[] tokenValue = textValue[0].split(";");

                for (String s : tokenValue) {
                    String[] value = s.split("=");
                    map.put(value[0], value[1]);
                }

                if ("winR".equals(map.get("company"))
                        && "WWCP".equals(map.get("appType"))
                        && appId.equals(map.get("appId"))
                        && map.containsKey("userId")) {
                    str[0] = "1";
                    str[1] = CommonResp.ok().getMsg();
                    str[2] = map.get("userId");
                } else {
                    str[0] = "0";
                    str[1] = CommonResp.fail().getMsg();
                }
            } else {
                str[0] = "0";
                str[1] = CommonResp.fail().getMsg();
            }
        } catch (Exception var16) {
            str[0] = "-1";
            str[1] = CommonResp.fail().getMsg();
            log.error("验证失败,出异常" + authentication, var16);
        }

        return str;
    }

    public static String createToken(String userId, String tokenKey) {
        String authenticator = "";

        try {
            Date now = new Date();
            SimpleDateFormat d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String appId = "appId";
            String digest = createDigest(appId);
            String orgToken = "company=winR;appType=WWCP;appId=" + appId + ";userId=" + userId + ";currentTime=" + d1.format(now) + "$" + digest;
            byte[] tripleKey = getKeyBytes(tokenKey);
            SecretKey secretKey = new SecretKeySpec(tripleKey, "DESede");
            Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            IvParameterSpec ivparam = new IvParameterSpec(iv);
            cipher.init(1, secretKey, ivparam);
            byte[] encriptText = cipher.doFinal(orgToken.getBytes(StandardCharsets.UTF_8));

            authenticator = authenticator + Base64.getEncoder().encodeToString(encriptText);
            authenticator = getStringNoBlank(authenticator);
        } catch (Exception var14) {
            log.error("异常信息", var14);
        }

        return authenticator;
    }

    public static String getStringNoBlank(String str) {
        if (str != null && !"".equals(str)) {
            Matcher m = BLANK_OR_LINE.matcher(str);
            return m.replaceAll("");
        } else {
            return str;
        }
    }

}
